#include <stdio.h>
#include <string.h>
#include <math.h>
#include <iostream>
#include <freetype2/ft2build.h>
#include <stdio.h>
#include FT_FREETYPE_H

void draw_bitmap(char ch,FT_Bitmap* bitmap)
{
    FT_Int  i, j, p, q;
    FT_Int  x_max = bitmap->width;
    FT_Int  y_max = bitmap->rows;

    char* ptr = new char[x_max*y_max];

    for(i = 0, p = 0; i < x_max; i++, p++)
    {
        for(j = 0, q = 0; j < y_max; j++, q++)
        {
            if(i < 0 || j < 0)
                continue;
            ptr[j*x_max+i] = bitmap->buffer[q * bitmap->width + p] == 0 ? '0': '*';
        }
    }

    std::cout<<"width:"<<x_max<<",height:"<<y_max<<"\n";
    for(i = 0; i < y_max; i++)
    {
       putchar('"');
       for(j = 0; j < x_max; j++)
          putchar(ptr[i*x_max+j]);
       putchar('"');
       putchar('\n');
    }
    putchar(';');

    delete []ptr;
}

int main(int argc,char**  argv)
{
    FT_Library    library;
    FT_Face       face;

    FT_GlyphSlot  slot;
    FT_Matrix     matrix;
    FT_Vector     pen;
    FT_Error      error;

    char*         filename;
    char*         text;

    double        angle;
    int           target_height = 13;
    int           n, num_chars;

    if(argc != 2)
    {
        fprintf(stderr,"usage: %s font sample-text\n",argv[0]);
        return -1;
    }

    filename      = argv[1];
    text          = "1234567890:fps";
    num_chars     = strlen(text);
    angle         = (0.0/360) * 3.14159 * 2;

    error = FT_Init_FreeType(&library);
    error = FT_New_Face(library,argv[1],0,&face);

    FT_Set_Pixel_Sizes(face,36,0);
    slot = face->glyph;
    matrix.xx = (FT_Fixed)(cos(angle)*0x10000L);
    matrix.xy = (FT_Fixed)(-sin(angle)*0x10000L);
    matrix.yx = (FT_Fixed)(sin(angle)*0x10000L);
    matrix.yy = (FT_Fixed)(cos(angle)*0x10000L);

    pen.x = 0*64;
    pen.y = (target_height - 40) * 64;

    for(n = 0; n < num_chars; n++)
    {
        FT_Set_Transform(face,&matrix,&pen);

        error = FT_Load_Char(face,text[n],FT_LOAD_RENDER);
        if(error)
            continue;

        draw_bitmap(text[n],&slot->bitmap);

        pen.x += slot->advance.x;
        pen.y += slot->advance.y;
    }

    FT_Done_Face(face);
    FT_Done_FreeType(library);
    return 0;
}


